package com.zhongjinkang.rhythm.network

import android.util.Log
import com.google.gson.Gson
import com.zhongjinkang.rhythm.BuildConfig
import com.zhongjinkang.rhythm.network.api.HttpCallBack
import com.zhongjinkang.rhythm.network.api.RequestApi
import com.zhongjinkang.rhythm.network.res.BaseResponse
import com.zhongjinkang.rhythm.network.res.UserRes
import com.zhongjinkang.rhythm.viewModel.PublicViewModel
import okhttp3.Request
import okhttp3.RequestBody
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import java.nio.charset.Charset


object HttpUtil {


    fun getUserInfo(token: String, httpCallBack: HttpCallBack<UserRes>) {
        RequestBuilder().getApi(RequestApi::class.java).getInfo(token).let { it ->
            try {
                val buffer = okio.Buffer()
                val request: Request = it.request()
                val body: RequestBody? = request.body()
                if (body != null) {
                    body.writeTo(buffer)
                    val url: String = it.request().url().toString()
                    HttpLog("发送数据:url:" + url + " \n内容:" + buffer.readString(Charset.defaultCharset()))
                } else {
                    HttpLog("发送数据:" + request.toString())
                }

                it.enqueue(object : Callback<BaseResponse<UserRes>> {
                    override fun onResponse(
                        call: Call<BaseResponse<UserRes>>,
                        response: Response<BaseResponse<UserRes>>
                    ) {
                        HttpLog("接收数据: onSuccess: " + Gson().toJson(response.body()))


                        response.body()?.let {
                            if (it.code == 200) {
                                it.data?.let { it1 -> httpCallBack.onSuccess(it1) }

                            } else if (it.code == 406) {
                                PublicViewModel.tokenState.value =
                                    PublicViewModel.TokenState.EFFECTIVE
                            } else {
                                httpCallBack.onFail(it.code, it.message)
                            }
                        }

                        PublicViewModel.loadingState.value =
                            PublicViewModel.LoadingState.LOAD_HIDE
                    }

                    override fun onFailure(call: Call<BaseResponse<UserRes>>, t: Throwable) {
                        httpCallBack.onFail(404, t.message.toString())

                        PublicViewModel.loadingState.value = PublicViewModel.LoadingState.LOAD_HIDE

                    }


                })

            } catch (e: Exception) {
                HttpLog("发送数据:解析失败")
                e.printStackTrace()
            }

        }


    }

    fun HttpLog(msg: String) {
        if (BuildConfig.DEBUG) {
            Log.i("Net", msg)
        }
    }
}